from machine import UART,Pin,RTC
import time
import common

wifi_config = common.get_config("wifi")
uart1 = UART(1, baudrate=115200, tx=Pin(4), rx=Pin(5), timeout_char=0, txbuf=256, rxbuf=256)
domain = 'www.hanxiaoxin.cn'

device_info = common.get_config("device_info")
device_id = common.get_config("device_id")
mcu = device_info["mcu"]
size = device_info["size"]
address = device_info["address"]
sensors = device_info["sensors"]
user_agent = f"device_id/{device_id} {mcu}/{size} address/{address} sensors/{sensors}"

def string_to_hex(s):
    return s.encode('utf-8').hex()

def transformPayload(payload):
    return bytes.fromhex(string_to_hex(payload))

def waitTime(wait = 0):
    start = time.ticks_ms()
    
    msg = ''
    while True:
        if uart1.any():
           line = uart1.read()
           msg = msg + str(line)
        now = time.ticks_ms()
        diff = now - start
        if diff > wait:
            start = now
            break
    print(msg)
    return msg

def connectWiFi():
    print('send wifi at....')
    uart1.write('AT+RESTORE\r\n')
    waitTime(2000)
    uart1.write('AT+RST\r\n')
    waitTime(1000)
    uart1.write('AT+CWMODE=1\r\n')
    waitTime(400)
    #uart1.write('AT+CIPDINFO=1\r\n')
    #waitTime(300)
    #uart1.write('AT+CWLAPOPT=1,31\r\n')
    #waitTime(500)
    #uart1.write('AT+CWLAP\r\n')
    #waitTime(3000)
    uart1.write(f'AT+CWJAP="{wifi_config["ssid"]}","{wifi_config["password"]}"\r\n')
    waitTime(10000)
    
def connectServer(input_domain, port = 80):
    #uart1.write('AT+CIPDOMAIN="' + domain + '"\r\n')
    #waitTime(1200)
    global domain
    domain = input_domain
    cmd = 'AT+CIPSTART="TCP","' + domain + f'",{port}\r\n'
    #print(cmd)
    uart1.write(cmd)
    waitTime(3000)
    
def readTCPResponse(wait):
    start = time.ticks_ms()
    msg = ''
    received_data = bytearray()
    while True:
        if uart1.any():
           line = uart1.read()
           received_data.extend(line)
           msg = msg + str(line)
        now = time.ticks_ms()
        diff = now - start
        if diff > wait:
            start = now
            break
    resp = msg.split('\\r\\n')
    #print(resp)
    #with open('log.txt', 'a+') as f:
    #    for line in resp:
    #        #print(line)
    #        f.write(line + '\n')
    close_request()
    return received_data

def getReceiveDataInfo():
    uart1.write('AT+CIPRECVLEN?\r\n')
    waitTime(1000)

def send_request(cmd):
    uart1.write('AT+CIPSEND=' + str(len(cmd)) + '\r\n')
    waitTime(300)
    paylod = transformPayload(cmd)
    #with open('log.txt', 'a+') as f:
    #    f.write(cmd + '\n')
    #print(cmd)
    print(paylod)
    uart1.write(paylod)
    return readTCPResponse(6000)

def close_request():
    uart1.write('AT+CIPCLOSE\r\n')
    waitTime(300)
    
def GET(path = '/'):
    cmd = f'GET {path} HTTP/1.1\r\nHost: ' + domain + f'\r\nUser-Agent: {user_agent}\r\n\r\n' #Connection: close\r\n\r\n
    return send_request(cmd)
    

def upload_data(topic):
    cmd = "{" + f'"op":"upload", "name":"data","topic":"{topic}", "data": "1,2,3,4"' + '}'
    return send_request(cmd)

def check_trigger_btn(topic):
    cmd = "{" + f'"op":"query", "name":"switch","topic":"{topic}"' + '}'
    return send_request(cmd)

def visit_msg_room():
    cmd = f'GET /room HTTP/1.1\r\nHost: ' + domain + f'\r\nUser-Agent: {user_agent}\r\nConnection: close\r\n\r\n'
    return send_request(cmd)

def get_room_msg():
    cmd = f'GET /msg HTTP/1.1\r\nHost: ' + domain + f'\r\nUser-Agent: {user_agent}\r\nConnection: close\r\n\r\n'
    return send_request(cmd)



